import { usePagination } from 'alova/client'
import {
  Input,
  Select,
  TableProps,
  Button,
  Card,
  Empty,
  Space,
  Table,
  DatePicker,
  Typography,
  List,
} from 'antd'
import React, { useEffect, useState } from 'react'
import { data, useNavigate } from 'react-router-dom'
import { MaintainVO, UserOpenAccountPageVO } from '../api/globals'
import TableFilter, { FilterItemConfig } from '../components/TableFilter'
import { formatDate } from '../uitls/common'
import { Dayjs } from 'dayjs'

const { Title, Text } = Typography

const MaintainList: React.FC = () => {
  const [filterParams, setFilterParams] = useState<
    Record<string, string | number | [string, string] | undefined>
  >({})
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [selectedRows, setSelectedRows] = useState<UserOpenAccountPageVO[]>([])

  const [isMobile, setIsMobile] = useState(false)
  useEffect(() => {
    const checkIfMobile = () => {
      setIsMobile(window.innerWidth <= 768)
    }

    // Initial check
    checkIfMobile()

    // Add event listener for window resize
    window.addEventListener('resize', checkIfMobile)

    // Cleanup
    return () => window.removeEventListener('resize', checkIfMobile)
  }, [])

  const navigate = useNavigate()

  const filters: FilterItemConfig[] = [
    {
      key: 'contactName',
      label: '用户名称',
      type: 'input',
      placeholder: '请输入姓名',
      component: <Input placeholder="请输入姓名" allowClear />,
    },
    {
      key: 'contactMobile',
      label: '手机号码',
      type: 'input',
      placeholder: '请输入手机号码',
      component: <Input placeholder="请输入手机号码" allowClear />,
    },
    {
      key: 'contractCode',
      label: '合同号',
      type: 'input',
      placeholder: '请输入合同号',
      component: <Input placeholder="请输入合同号" allowClear />,
    },
    // {
    //   key: 'houseId',
    //   label: '户号',
    //   type: 'input',
    //   placeholder: '请输入户号',
    //   component: <Input placeholder="请输入户号" allowClear />,
    // },
    {
      key: 'productId',
      label: '产品id',
      type: 'select',
      placeholder: '请选择产品',
      component: (
        <Select
          placeholder="请选择"
          allowClear
          style={{ width: '100%' }}
          options={[
            { label: '产品1', value: 1 },
            { label: '产品2', value: 2 },
            { label: '产品3', value: 3 },
          ]}
        />
      ),
    },
    {
      key: 'address',
      label: '用户地址',
      type: 'input',
      component: <Input placeholder="请输入用户地址" allowClear />,
    },
    {
      key: 'day',
      label: '维保日期',
      type: 'date',
      span: 16,
      component: <DatePicker style={{ width: '100%' }} />,
    },
  ]

  // 处理搜索
  const handleSearch = (values: Record<string, unknown>) => {
    setFilterParams(
      values as Record<string, string | number | [string, string] | undefined>
    )
  }

  // 处理重置
  const handleReset = () => {
    setFilterParams({})
  }

  const MobileOrderCard = ({ record }: { record: MaintainVO }) => {
    const getActionButton = () => {
      return (
        <Button
          type="primary"
          size="small"
          onClick={() => navigate(`/mt/detail/${record.maintainBatch}`)}
        >
          详情
        </Button>
      )
    }

    return (
      <Card size="small" className="mb-3" actions={[getActionButton()]}>
        <div className="flex justify-between mb-2">
          <Text strong>{record.name}</Text>
        </div>
        <div className="mb-1">
          <Text type="secondary">手机: </Text>
          <Text>{record.contactMobile}</Text>
        </div>
        <div className="mb-1">
          <Text type="secondary">合同号: </Text>
          <Text>{record.contractCode}</Text>
        </div>
        <div>
          <Text type="secondary">批次号: </Text>
          <Text>{record.maintainBatch}</Text>
        </div>
      </Card>
    )
  }

  const columns: TableProps<MaintainVO>['columns'] = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_, __, index) => index + 1,
    },
    {
      title: '户号',
      dataIndex: 'houseCode',
      key: 'houseCode',
    },
    {
      title: '小区名称',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '维保时间',
      dataIndex: 'time',
      key: 'time',
      render: (_, record) => {
        return record.time ? formatDate(record.time) : ''
      },
    },
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户手机号',
      dataIndex: 'contactMobile',
      key: 'contactMobile',
    },
    {
      title: '合同号',
      dataIndex: 'contractCode',
      key: 'contractCode',
    },
    {
      title: '维保批次号',
      dataIndex: 'maintainBatch',
      key: 'maintainBatch',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => navigate(`/mt/detail/${record.maintainBatch}`)}>
            查看
          </a>
        </Space>
      ),
    },
  ]

  const rowSelection: TableProps<UserOpenAccountPageVO>['rowSelection'] = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows
      )
      setSelectedRowKeys(selectedRowKeys)
      setSelectedRows(selectedRows)
    },
  }

  const {
    data: orderList,
    loading,
    error,
    page,
    pageSize,
    total,
    update,
    refresh,
  } = usePagination(
    (page, pageSize) => {
      let pureFilterParams: Record<
        string,
        string | number | [string, string] | undefined
      > = {}
      if (filterParams) {
        pureFilterParams = Object.fromEntries(
          Object.entries(filterParams).filter(
            ([, value]) => value !== undefined && value !== null
          ) as [string, string | number | [string, string] | undefined][]
        )
        if (pureFilterParams.day) {
          pureFilterParams.day = (
            pureFilterParams.day as unknown as Dayjs
          ).format('YYYY-MM-DD')
        }
      }
      return Apis.mt.Page({
        params: {
          pageNum: page,
          pageSize: pageSize,
          ...pureFilterParams,
        },
      })
    },
    {
      immediate: true,
      data: (response) => response.records,
      total: (response) => response.total,
      watchingStates: [filterParams],
    }
  )

  return (
    <div className="h-full flex flex-col">
      <Card variant="borderless" className="mb-4">
        <div className="flex justify-between items-center mb-4">
          <Title level={4} className="!mb-0">
            郑水净界·维保记录列表
          </Title>
          <Button
            type="primary"
            className="!bg-success"
            onClick={() => navigate('/mt/add')}
          >
            新建维保记录
          </Button>
        </div>

        <TableFilter
          filters={filters}
          onSearch={handleSearch}
          onReset={handleReset}
          initialValues={{ status: 0 }}
          showDivider={false}
        />
      </Card>

      <Card variant="borderless" className="flex-1">
        {error ? (
          <div className="w-full flex justify-center items-center py-8">
            <Empty
              description={
                <Space direction="vertical" align="center">
                  <span className="text-red-500 font-medium">
                    {(error as unknown as { msg: string }).msg}
                  </span>
                  <Button type="primary" onClick={() => refresh()}>
                    刷新
                  </Button>
                </Space>
              }
            />
          </div>
        ) : isMobile ? (
          <List
            dataSource={orderList}
            renderItem={(record) => <MobileOrderCard record={record} />}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              onChange: (page, pageSize) => update({ page, pageSize }),
              size: 'small',
              simple: true,
              showSizeChanger: false,
            }}
          />
        ) : (
          <Table
            rowKey="id"
            columns={columns}
            dataSource={orderList}
            loading={loading}
            rowSelection={rowSelection}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
              onChange: (page, pageSize) => {
                update({ page, pageSize })
              },
            }}
            scroll={{ x: 1200, y: 600 }}
          />
        )}
      </Card>
    </div>
  )
}

export default MaintainList
